package com.digital.welcome.exception;


import com.alibaba.fastjson.JSON;
import com.digital.welcome.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * @PackageName:com.ye.back.exception
 * @ClassName:GlobalException
 * @Description:
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(value = UnauthorizedException.class)
    public String handler(UnauthorizedException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return JSON.toJSONString(new Result<>().setCode(402).setMessage("无权限操作"));
    }

    @ExceptionHandler(value = ExpiredCredentialsException.class)
    public String handler(ExpiredCredentialsException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return JSON.toJSONString(new Result<>().setCode(401).setMessage("登录已过期，请重新登录"));
    }


    @ExceptionHandler(value = UnauthenticatedException.class)
    public String handler(UnauthenticatedException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return JSON.toJSONString(new Result<>().setCode(401).setMessage("未登录"));
    }

    @ExceptionHandler(value = UnknownAccountException.class)
    public String handler(UnknownAccountException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return JSON.toJSONString(new Result<>().setCode(401).setMessage("未登录123"));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public String handleBindException(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolationSets = ex.getConstraintViolations();

        return JSON.toJSONString(new Result<>().setCode(401).setMessage(constraintViolationSets.iterator().next().getMessage()));
    }
}
